#include <stdio.h>
#include <stdlib.h>
#include "errno.h"
#include "config.h"
#include "simulator.h"

void native_plugin_start() {
	const char *plugin_path;
	int i, f, n = config_count("NATIVE_PLUGIN");

	for (i = 0; i < n; i++) {
		plugin_path = config_get("NATIVE_PLUGIN", i);
		if ((f = fork()) == 0) {
			if (system(plugin_path) < 0)
				fprintf(stderr, "chipmuck: unable to execute native plugin %s.\n", plugin_path);
			exit(0);
		}
		else if (f == -1)
			fprintf(stderr, "chipmuck: unable to fork a native plugin.\n");
	}
}

int main() {
	int r;
	char *config_name = "chipmuck.conf";
	
	if ((r = config_read(config_name)) != 0) {
		if (r != -E_FILE_NOT_EXIST) {
			fprintf(stderr, "chipmuck: cannot read config file %s, errno=%d.\n", config_name, -r);
			return 1;
		}
		if ((r = config_create(config_name)) != 0) {
			fprintf(stderr, "chipmuck: cannot create new config file %s, errno=%d.\n", config_name, -r);
			return 1;
		}
	}

	if ((r = simulator_start()) != 0) {
		fprintf(stderr, "chipmuck: cannot start the simulator, errno=%d.\n", -r);
		return 1;
	}
	if ((r = mediator_listen()) != 0) {
		fprintf(stderr, "chipmuck: error on connection, errno=%d.\n", -r);
		return 1;
	}
	native_plugin_start();
	mediator_work();
	mediator_stop();
	simulator_stop();

	return 0;
}
